<template>
  <div class="product-management">

    <!-- 操作按钮 -->
    <a-card style="margin-top: 16px" class="table-body">
      <div class="table-contaier" ref="tableContainerRef">
        <a-table :scroll="{ y: tableHeight + 'px' }" :loading="loading" :columns="columns" :data-source="orderList"
          :pagination="pagination" row-key="order_id" @change="handleTableChange">
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.key === 'index'">
              {{ index + 1 }}
            </template>
            <template v-if="column.key === 'user_name'">
              {{ record.user.username }}
            </template>
            <template v-if="column.key === 'address'">
              {{ formatAddress(record.user.address) }}
            </template>
            <template v-if="column.key === 'order_amount'">
              {{ Number(record.order_amount).toFixed(2) }}
            </template>
            <template v-if="column.key === 'rating'">
              <a-rate :value="record.rating" disabled />
            </template>
            <template v-if="column.key === 'create_time' || column.key === 'createdAt'">
              {{ record[column.key] ? formatTime(record[column.key]) : '' }}
            </template>
            <template v-else-if="column.key === 'action'">
              <a-space>
                <a-button type="link" @click="confirmDelete(record)">删除评论</a-button>
              </a-space>
            </template>
          </template>
          <template #expandedRowRender="{ record }">
            <a-table style="padding: 10px;" :columns="productColumns" :data-source="record.productList ?? []"
              :pagination="false" row-key="user_id">
              <template #bodyCell="{ column, record, index }">
                <template v-if="column.key === 'index'">
                  {{ index + 1 }}
                </template>
                <template v-if="column.key === 'image'">
                  <a-image :width="40" :src="record.image"
                    fallback="" />
                </template>
                <template v-if="column.key === 'type'">
                  {{ formatType(record.type) }}
                </template>
                <template v-if="column.key === 'mark'">
                  {{ formatMark(record.mark) }}
                </template>
                <template v-if="column.key === 'state'">
                  {{ formatState(record.state) }}
                </template>
              </template>
            </a-table>
          </template>
        </a-table>
      </div>
    </a-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import {
  message,Modal
} from 'ant-design-vue'
import moment from 'moment';
import { queryAllReviews, delReview } from '@/apis/admin/order'
import { codeToText } from 'element-china-area-data';

// 数据状态
const orderList = ref([])
const loading = ref(false)

const tableContainerRef = ref();
const tableHeight = ref(600);
onMounted(() => {
  tableHeight.value = tableContainerRef.value.clientHeight - 88;
})



// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 8,
  total: 0,
  showSizeChanger: false,
  showTotal: total => `总共 ${total} 条`
})

// 表格列配置
const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    width: '100px',
    key: 'index',
  },
  {
    title: '订单号',
    dataIndex: 'order_no',
    width: '140px',
    key: 'order_no'
  },

  {
    title: '用户ID',
    dataIndex: 'user_id',
    width: '100px',
    key: 'user_id'
  },
  {
    title: '用户名称',
    dataIndex: 'user_name',
    width: '140px',
    key: 'user_name'
  },
  {
    title: '评价分数',
    dataIndex: 'rating',
    width: '220px',
    key: 'rating'
  },
  {
    title: '评价内容',
    dataIndex: 'content',
    width: '140px',
    key: 'content'
  },
  {
    title: '评价时间',
    dataIndex: 'createdAt',
    width: '140px',
    key: 'createdAt'
  },
  {
    title: '订单地址',
    dataIndex: 'address',
    width: '240px',
    key: 'address'
  },
  {
    title: '订单时间',
    dataIndex: 'create_time',
    width: '200px',
    key: 'create_time'
  },
  {
    title: '订单金额',
    dataIndex: 'order_amount',
    width: '100px',
    key: 'order_amount'
  },
  {
    title: '操作',
    key: 'action',
    width: '100px',
    fixed: 'right'
  }
]

const productColumns = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
  },
  {
    title: '外卖图片',
    dataIndex: 'image',
    key: 'image'
  },
  {
    title: '外卖名称',
    dataIndex: 'title',
    key: 'title'
  },
  {
    title: '外卖描述',
    dataIndex: 'spec',
    key: 'spec'
  },
  {
    title: '价格(元)',
    key: 'originalPrice',
    dataIndex: 'originalPrice'
  },
  {
    title: '折后价(元)',
    key: 'price',
    dataIndex: 'price'
  },
  {
    title: '数量',
    key: 'quantity',
    dataIndex: 'quantity'
  },
]

const confirmDelete = async (record) => {
  Modal.confirm({
    title: `你确定要删除该评论？`,
    content: '',
    centered: true,
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      const res = await delReview(record.id)
      if (res.code === 0) {
        message.success('删除成功')
        fetchOrderList()
      } else {
        message.error(res.message)
      }
    }
  });

}

// 生命周期钩子
onMounted(() => {
  fetchOrderList()
})

// 方法
const fetchOrderList = async () => {
  try {
    loading.value = true

    const params = {
      page: pagination.current,
      limit: pagination.pageSize,
    }
    for (let keys in params) {
      if (params[keys] === null || params[keys] === undefined || params[keys] === '') delete params[keys]
    }

    const res = await queryAllReviews(params)
    if (res.code === 0) {
      orderList.value = res.data.list.map(item => {
        return {
          ...item,
          create_time: item.order.create_time,
          order_amount: item.order.order_amount,
          order_no: item.order.order_no,
          productList: JSON.parse(item.order.product)
        }
      });

      pagination.total = res.data.total
    } else {
      message.error(res.message)
    }
  } catch (error) {
    message.error('获取产品列表失败')
  } finally {
    loading.value = false
  }
}



const handleTableChange = (pag, filters, sorter) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchOrderList()
}


// 格式化时间
const formatTime = (time) => {
  return moment(time).format('YYYY-MM-DD HH:mm:ss');
};

const formatAddress = (address) => {
  let addr = '';
  let region = [];
  if (address) {
    address = JSON.parse(address);
    if (Array.isArray(address) && address.length >= 4) {
      region = address.slice(0, 3);
      addr = address.slice(3, 4)
    }
  }
  return region.length >= 3 ? convertCodesToText(region) + ' ' + addr : addr;
}
function convertCodesToText(codes) {
  return codes.map(code => {
    return codeToText[code] || '未知地区'
  }).join(' ')
}

function formatType(type) {
  if (type === 1) {
    return '主食'
  } else if (type === 2) {
    return '饮料'
  } else if (type === 3) {
    return '小吃'
  } else if (type === 4) {
    return '水果'
  } else {
    return ''
  }
}

function formatState(state) {
  if (state === 1) {
    return '上架'
  } else {
    return '未上架'
  }
}

function formatMark(mark) {
  if (mark === 1) {
    return '新品'
  } else if (mark === 2) {
    return '招牌'
  } else if (mark === 3) {
    return '推荐'
  } else {
    return '推荐'
  }
}





</script>

<style lang="less" scoped>
.product-management {
  padding: 20px;
  display: flex;
  flex-direction: column;

  .user-form {
    width: 100%;
    display: flex;
    justify-content: space-between;

    .form-btn {
      min-width: 140px;
    }
  }

  .table-body {
    flex: 1;

    :deep(.ant-card-body) {
      height: 100%;
      display: flex;
      flex-direction: column;

      .table-contaier {
        flex: 1;

        .ant-table {
          height: 100%;
        }
      }

    }
  }
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.ant-card {
  margin-bottom: 16px;
}
</style>